package com.hae.shop.micoshoporderservice.controller;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.util.BeanConvertUtil;
import com.hae.shop.common.util.transaction.RedisDataSoureceTransaction;
import com.hae.shop.micoshoporderservice.constant.BizErrorEnum;
import com.hae.shop.micoshoporderservice.feign.PayFeign;
import com.hae.shop.micoshoporderservice.mapper.OrderMapper;
import com.hae.shop.micoshoporderservice.mapper.model.OrderDo;
import com.hae.shop.order.api.OrderService;
import com.hae.shop.order.model.OrderReqDto;
import com.hae.shop.pay.model.reqDto.GetPayTokenReqDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 订单服务接口实现
 */
@RestController
@Validated
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private PayFeign feign;

    @Autowired
    private RedisDataSoureceTransaction manualTransaction;

    @Override
    @RequestMapping("/createOrder")
    public Response<String> createOrder(@RequestBody OrderReqDto orderReqDto) throws Exception {
        Response<String> response = new Response<>();
        //2.开启事务
        TransactionStatus transactionStatus = manualTransaction.begin();
        try {
            //调用Mapper接口在数据库新建记录
            OrderDo orderDo = BeanConvertUtil.EToT(orderReqDto, OrderDo.class);
            int insertResult = orderMapper.createOrder(orderDo);
            if (insertResult < 0) {
                throw new RuntimeException(BizErrorEnum.INSERT_ORDER_RECORD_FAILED.getErrorMsg());
            }
            //调用支付服务生成支付token
            Response<String> createPayToken = feign.getPayToken(BeanConvertUtil.EToT(orderDo, GetPayTokenReqDto.class));
            if (!createPayToken.isSuccess()) {
                throw new RuntimeException(BizErrorEnum.TRANSFER_PAY_SERVICE_EXCEPTION.getErrorMsg());
            }
            // 没有问题则提交事务
            manualTransaction.commit(transactionStatus);
            response.setResult(createPayToken.getResult());
        }catch (Exception e) {
            // 回滚事务并抛出异常
            manualTransaction.rollback(transactionStatus);
            response.setResult(BizErrorEnum.CREATE_ORDER_FAILED.getErrorCode(),
                    BizErrorEnum.CREATE_ORDER_FAILED.getErrorMsg());
        }
        return response;
    }
}
